package com.longrise.co.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.longrise.android.IBaseListener;
import com.longrise.android.checkVersion.UpdataAPK;
import com.longrise.android.util.AppUtils;
import com.longrise.android.widget.OnRequestPremessionResultListener;
import com.longrise.co.R;
import com.longrise.co.api.ApiConstants;
import com.longrise.co.ui.carfiles.fragment.CarFileFragment;
import com.longrise.co.ui.carlife.fragment.CarLifeFragment;
import com.longrise.co.ui.home.fragment.HomeFragment;
import com.longrise.co.ui.mine.fragment.MineFragment;
import com.longrise.co.utils.Constants;
import com.ly.common.base.BaseFragment;
import com.ly.common.base.BaseFragmentAdapter;
import com.ly.common.base.BaseMainFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by luoyang on 2017-6-26.
 */

public class MainFragment extends BaseMainFragment implements ViewPager.OnPageChangeListener, IBaseListener {

    @Bind(R.id.main_content)
    ViewPager mainContent;
    @Bind(R.id.main_home_iv)
    ImageView mainHomeIv;
    @Bind(R.id.main_home_tv)
    TextView mainHomeTv;
    @Bind(R.id.main_car_file_iv)
    ImageView mainCarFileIv;
    @Bind(R.id.main_car_file_tv)
    TextView mainCarFileTv;
    @Bind(R.id.main_car_life_iv)
    ImageView mainCarLifeIv;
    @Bind(R.id.main_car_life_tv)
    TextView mainCarLifeTv;
    @Bind(R.id.main_mine_iv)
    ImageView mainMineIv;
    @Bind(R.id.main_mine_tv)
    TextView mainMineTv;

    private int mSelectColor;
    private int mUnSelectColor;

    private OnRequestPremessionResultListener mOnRequestPremessionResultListener;
    public static final int MY_PERMISSION_REQUEST_CODE = 123;

    private static final String[] PERMISSIONS_CONTACT = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE} ;
    private List<Fragment> list;

    @Override
    protected int getLayoutResource() {
        return R.layout.fg_main;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void initView() {

        mSelectColor = Color.parseColor("#098edd");
        mUnSelectColor = Color.parseColor("#666666");

        list = new ArrayList<>();
        list.add(HomeFragment.newInstance());
        list.add(CarFileFragment.newInstance());
        list.add(CarLifeFragment.newInstance());
        list.add(MineFragment.newInstance());

        BaseFragmentAdapter adapter = new BaseFragmentAdapter(getChildFragmentManager(), list);
        if(mainContent != null) {
            mainContent.setAdapter(adapter);
            mainContent.setOffscreenPageLimit(4);
            mainContent.addOnPageChangeListener(this);
        }
        setTab(0);
        registerRxEvent();
        int versionCode = AppUtils.getAppVersionCode(getContext());
        //检测更新
        UpdataAPK updataAPK = new UpdataAPK(getContext(), Constants.APP_NAME, ApiConstants.updateUrl+"restservices/appgetversion", ApiConstants.updateUrl, versionCode, this);
        updataAPK.checkVersion();
    }

    private void registerRxEvent() {
        mRxManager.on(Constants.RX_EVENT_QXDA, new Action1<Integer>() {
            @Override
            public void call(Integer i) {
                if(i >= 0  && i <= 3) {
                    mainContent.setCurrentItem(i,false);
                }
            }
        });

        mRxManager.on(Constants.RX_EVENT_NEXT_PAGE, new Action1<BaseFragment>() {
            @Override
            public void call(BaseFragment fragment) {
           start(fragment);
            }
        });

        mRxManager.on(Constants.RX_EVENT_UPDATE, new Action1<String>() {
            @Override
            public void call(String s) {
                if( mOnRequestPremessionResultListener != null) {
                    mOnRequestPremessionResultListener.onAllowPremession();
                }
            }
        });

    }

    @OnClick({R.id.main_home_rl, R.id.main_car_file_rl, R.id.main_car_life_rl, R.id.main_mine_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_home_rl:
                mainContent.setCurrentItem(0);
                break;
            case R.id.main_car_file_rl:
                mainContent.setCurrentItem(1);
                break;
            case R.id.main_car_life_rl:
                mainContent.setCurrentItem(2);
                break;
            case R.id.main_mine_rl:
                mainContent.setCurrentItem(3);
                break;
        }
    }

    private void setTab(int index) {
        clearAllTab();
        switch (index) {
            case 0 :
                if(mainHomeIv != null) {
                    mainHomeIv.setImageResource(R.drawable.home_select);
                }
                if(mainHomeTv != null) {
                    mainHomeTv.setTextColor(mSelectColor);
                }
                break;
            case 1 :
                if(mainCarFileIv != null) {
                    mainCarFileIv.setImageResource(R.drawable.carfile_select);
                }
                if(mainCarFileTv != null) {
                    mainCarFileTv.setTextColor(mSelectColor);
                }
                break;
            case 2 :
                if(mainCarLifeIv != null) {
                    mainCarLifeIv.setImageResource(R.drawable.carlife_select);
                }
                if(mainCarLifeTv != null) {
                    mainCarLifeTv.setTextColor(mSelectColor);
                }

                break;
            case 3 :
                if(mainMineIv != null) {
                    mainMineIv.setImageResource(R.drawable.mine_select);
                }
                if(mainMineTv != null) {
                    mainMineTv.setTextColor(mSelectColor);
                }
                break;
        }
    }

    private void clearAllTab() {
        if(mainHomeIv != null) {
            mainHomeIv.setImageResource(R.drawable.home_unselect);
        }

        if(mainCarFileIv != null) {
            mainCarFileIv.setImageResource(R.drawable.carfile_unselect);
        }

        if(mainCarLifeIv != null) {
            mainCarLifeIv.setImageResource(R.drawable.carlife_unselect);
        }

        if(mainMineIv != null) {
            mainMineIv.setImageResource(R.drawable.mine_unselect);
        }

        if(mainHomeTv != null) {
            mainHomeTv.setTextColor(mUnSelectColor);
        }

        if(mainCarFileTv != null) {
            mainCarFileTv.setTextColor(mUnSelectColor);
        }
        if(mainCarLifeTv != null) {
            mainCarLifeTv.setTextColor(mUnSelectColor);
        }
        if(mainMineTv != null) {
            mainMineTv.setTextColor(mUnSelectColor);
        }




    }

    public static MainFragment newInstance() {
        return  new MainFragment();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setTab(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void requestPermission(String permission, String noPresessionNotice, OnRequestPremessionResultListener onRequestPremessionResultListener) {
        this.mOnRequestPremessionResultListener = onRequestPremessionResultListener;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkUpdatePermission();
        } else {
            mOnRequestPremessionResultListener.onAllowPremession();
        }

    }

    private void checkUpdatePermission() {
        /**
         * 第 1 步: 检查是否有相应的权限
         */
        boolean isAllGranted = checkPermissionAllGranted(
                PERMISSIONS_CONTACT
        );
        // 如果这3个权限全都拥有, 则直接执行备份代码
        if (isAllGranted) {
            mOnRequestPremessionResultListener.onAllowPremession();
            return;
        }
        /**
         * 第 2 步: 请求权限
         */
        // 一次请求多个权限, 如果其他有权限是已经授予的将会自动忽略掉
        ActivityCompat.requestPermissions(
                _mActivity,
                PERMISSIONS_CONTACT,
                MY_PERMISSION_REQUEST_CODE
        );
    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(_mActivity, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                return false;
            }
        }
        return true;
    }

    @Override
    public void showNOPresessionDialog(int requestCode) {

    }

   /* @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;

            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                // 如果所有的权限都授予了, 则执行备份代码
                mOnRequestPremessionResultListener.onAllowPremession();
            } else {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
                showErrorTip("拒绝权限将影响App的正常使用!");
            }
        }
    }*/
}
